/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lb.trac.scheduling;

import java.util.Date;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.lb.trac.pojo.Evento;
import com.lb.trac.pojo.StoricoTicket;
import com.lb.trac.pojo.Tickets;
import com.lb.trac.service.MailSenderService;
import com.lb.trac.service.ManageTicketService;
import com.lb.trac.service.SearchService;

/**
 * 
 * @author edoardo
 */
public class JobEmailBean extends QuartzJobBean {

	private SearchService searchService;
	private ManageTicketService manageTicketService;
	private MailSenderService mailSenderService;
	private static long ultimoInvio;

	@Override
	protected void executeInternal(JobExecutionContext context)
			throws JobExecutionException {
		try {
			Evento[] eventi = searchService.findEventiDaInviare();
			Tickets t = new Tickets();
			long giornoInMs = 1000 * 60 * 60 * 24;

			for (int i = 0; i < eventi.length; i++) {
				Evento evento = eventi[i];
				StoricoTicket storicoTicket = evento.getStoricoTicket();
				Tickets tickets = null;
				if (storicoTicket != null) {
					tickets = storicoTicket.getTickets();
				} else {
					tickets = evento.getTickets();
				}
				String tipoEvento = evento.getTipoEvento();
				boolean isPromemoria = "PROMEMORIA"
						.equalsIgnoreCase(tipoEvento);
				mailSenderService.sendMessage(evento, tickets,
						isPromemoria ? MailSenderService.SEND_ONLY_TO_DEVELOPER
								: MailSenderService.SEND_TO_ALL);
				// manageTicketService.delete(evento);
				ultimoInvio = new Date().getTime();
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			throw new JobExecutionException(exception.getMessage());
		}
	}

	public ManageTicketService getManageTicketService() {
		return manageTicketService;
	}

	public void setManageTicketService(ManageTicketService manageTicketService) {
		this.manageTicketService = manageTicketService;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

	public MailSenderService getMailSenderService() {
		return mailSenderService;
	}

	public void setMailSenderService(MailSenderService mailSenderService) {
		this.mailSenderService = mailSenderService;
	}

}
